﻿using UnityEngine;
using UnityEngine.UI;
using System.Collections.Generic; //Must only use WinRT types: https://msdn.microsoft.com/en-ca/library/hh454064.aspx

namespace Assets.Custom_Scripts
{

    public class RelationshipController : MonoBehaviour
    {

        //private properties
        protected int[] _romanceScore = null;
        protected float _contactTimer = 0;
        protected bool _inRangeWithPLI = false;
        protected CountdownTimer _stopwatch;
        protected GameObject _inContactWith;


        //public properties
        public int FlowersReceived = 0;
        public GameObject[] PotentialLoveInterests;
        public float PersonalSpace = 0;
        protected List<GameObject> FlowersAcquired = new List<GameObject>();
        public Canvas RelationshipScoreUI;
        public int DefaultRomanceScore = 4;
        public string[] RelationshipLevels;
        public float MaxContactDuration = 0;
        public float ContactRange = 0;
        public string PlayerTag;
        public string PLITag;
        public string BullyTag;



        // Use this for initialization
        void Start()
        {
            if (null == PotentialLoveInterests || PotentialLoveInterests.Length < 1)
            {
                Debug.Log(@"Need to provide at least one potential love interest.");
                return;
            }
            _romanceScore = new int[PotentialLoveInterests.Length];

            for (int i = 0; i < PotentialLoveInterests.Length; i++)
            {
                _romanceScore[i] = DefaultRomanceScore;
            }

            //_stopwatch = GetComponentInParent<CountdownTimer>();
            //_stopwatch = GetComponent<CountdownTimer>();
            //Component[] components = GetComponentsInParent<CountdownTimer>();
            //_stopwatch = GetComponent(@"CountdownTimer");
            _stopwatch = gameObject.GetComponent<CountdownTimer>();

        }

        // Update is called once per frame
        void Update()
        {

            #region Housekeeping calls

            //updateContactDuration();

            #endregion Housekeeping Calls

            return;

            // update on-screen scoreboards
            for (int i = 0; i < PotentialLoveInterests.Length; i++)
            {

            }

        }


        public void AcquireFlowers(GameObject flowers)
        {
            if (null == flowers)
            {
                return;
            }

            FlowersAcquired.Add(flowers);
        }

        public void ReceiveFlowersFrom(GameObject giver)
        {

            Debug.Log(gameObject.tag + @"::ReceiveGiftFrom().");
            //logic to increase relationship with giver
            for (int i = 0; i < PotentialLoveInterests.Length; i++)
            {
                if (giver.tag.Equals(PotentialLoveInterests[i].tag))
                {
                    _romanceScore[i]++;
                    DisplayRelationshipPoints(i);
                    FlowersReceived++;
                    ParticleSystem floatingHearts = gameObject.GetComponent<ParticleSystem>();
                    floatingHearts.Play();
                    return;
                }
            }

        }


        public void FixedUpdate()
        {

            GameObject loveInterestInProximity = CollidedWithPotentialLoveInterest();

            #region Player logic

            if (gameObject.tag.Contains(PlayerTag))
            {


                if (null != loveInterestInProximity)
                {
                    if (HaveGift())
                    {
                        GiveGift(loveInterestInProximity);
                    }
                    else
                    {
                        if ((_stopwatch as CountdownTimer).TimeLeft <= 0)
                        {
                            loveInterestInProximity.SendMessage(@"TriggerEmotionalReaction", gameObject);
                        }
                    }
                }

            }

            #endregion Player logic

            #region PLI logic

            else if (gameObject.tag.Contains(PLITag))
            {

            }

            #endregion PLI logic

        }

        GameObject CollidedWithPotentialLoveInterest()
        {
            if (PotentialLoveInterests != null)
            {
                if (PotentialLoveInterests.Length > 0)
                {
                    for (int i = 0; i < PotentialLoveInterests.Length; i++)
                    {
                        Vector3 distanceBetweenVector = transform.position - PotentialLoveInterests[i].transform.position;
                        float distanceBetween = distanceBetweenVector.magnitude;

                        if (distanceBetween <= PersonalSpace)
                        {
                            startCountingContactDuration();
                            _inContactWith = PotentialLoveInterests[i];
                            return PotentialLoveInterests[i];
                        }
                        else
                        {
                            stopCountingContactDuration();
                            _inContactWith = null;
                            return null;
                        }
                    }
                }
            }


            return null;

        }

        public void GiveGift(GameObject potentialLoveInterest)
        {

            Vector3 distanceBetweenCharactersVector = transform.position - potentialLoveInterest.transform.position;
            if (distanceBetweenCharactersVector.magnitude > ContactRange)
            {
                return;
            }

            if (FlowersAcquired.Count > 0)
            {

                //send message to woman to boost romance level.
                potentialLoveInterest.SendMessage(@"ReceiveFlowersFrom", gameObject);

                GameObject flowers = FlowersAcquired[0] as GameObject;
                Destroy(flowers);
                FlowersAcquired.RemoveAt(0);

            }

        }

        public bool HaveGift()
        {
            if (FlowersAcquired.Count > 0)
            {
                return true;
            }

            return false;
        }

        public void DisplayRelationshipPoints(int indexOfPotentialLoveInterest)
        {

            Canvas currentPLIScore = RelationshipScoreUI;
            string pliName = PotentialLoveInterests[indexOfPotentialLoveInterest].tag + @" " + (indexOfPotentialLoveInterest + 1).ToString() + @" Score: ";
            Text scorePlaceholder = currentPLIScore.GetComponentInChildren<Text>();
            int descriptionIndex = _romanceScore[indexOfPotentialLoveInterest];
            string scoreText = pliName + @" " + RelationshipLevels[descriptionIndex] + @".";
            scorePlaceholder.text = scoreText;

        }

        public void HideRelationshipPoints()
        {
            Canvas relationshipScoreUI = RelationshipScoreUI;
            Text scorePlaceholder = relationshipScoreUI.GetComponentInChildren<Text>();
            scorePlaceholder.text = string.Empty;

        }

        public void TriggerEmotionalReaction()
        {
            Debug.Log(gameObject.tag + @"::EmotionalReaction().");

            //logic to decrease relationship with giver
            for (int i = 0; i < PotentialLoveInterests.Length; i++)
            {
                if (_inContactWith.tag.Equals(PotentialLoveInterests[i].tag))
                {
                    if (_contactTimer > MaxContactDuration)
                    {
                        if (_romanceScore[i] > 0)
                        {
                            _romanceScore[i]--;
                        }
                        DisplayRelationshipPoints(i);
                        return;
                    }
                }
            }

        }

        protected void startCountingContactDuration()
        {
            _inRangeWithPLI = true;
            //_contactTimer += 1 * Time.deltaTime;
            //_stopwatch.St
            //_stopwatch.TimeLeft = _stopwatch.TimeAllowed;
            if (_stopwatch != null)
            {
                _stopwatch.BeginCounting();
            }
            
        }

        protected void stopCountingContactDuration()
        {
            _inRangeWithPLI = false;
            //_contactTimer = 0;
            if (_stopwatch != null)
            {
                _stopwatch.StopCounting();
            }
        }

        protected void updateContactDuration()
        {
            Debug.Log(gameObject.tag + @" in contact with PLI for " + _stopwatch.TimeLeft.ToString() + @"s.");
            return;

            if (_inRangeWithPLI == true)
            {
                _contactTimer += 1 * Time.deltaTime;
                Debug.Log(gameObject.tag + @" in contact with PLI for " + _stopwatch.TimeLeft.ToString() + @"s.");
            }
        }

    }

}